<template>
  <div>
    <el-form ref="editForm" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-row :gutter="40">
        <!-- <el-col :span="12">
          <el-form-item label="名称" required prop="title">
            <el-input v-model="formItem.title" placeholder="请输入规则名称" :maxlength="255" />
          </el-form-item>
        </el-col> -->
        <el-col :span="6">
          <el-form-item label="分类：">
            <span>{{ formItem.knowledgeTypeName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="关键字：">
            <!-- <el-input v-model="test" placeholder="输入关键字，按回车添加" @change="add" /> -->
            <el-tag v-for="tag in formItem.keywords" :key="tag.name" size="mini" type="danger">{{ tag.name }}</el-tag>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="创建人：">
            <span>{{ formItem.userName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发布时间：">
            <span>{{ formItem.createTime }}</span>
          </el-form-item>
        </el-col>
        <el-col v-if="formItem.updateUserCode!=null" :span="6">
          <el-form-item label="更新人：">
            <span>{{ formItem.updateUserName }}</span>
          </el-form-item>
        </el-col>
        <el-col v-if="formItem.updateUserCode!=null" :span="6">
          <el-form-item label="更新时间：">
            <span>{{ formItem.updateTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="内容：">
            <p v-html="formItem.content" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="附件列表：">
            <!-- <el-tag v-for="tag in formItem.attachment" :key="tag.name" size="mini" type="info" @click.native="clickTag(tag)">{{ tag.name }}</el-tag> -->
            <el-button v-for="tag in formItem.attachment" :key="tag.name" size="mini" type="text" @click.native="clickTag(tag)">{{ tag.name }}</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="评论">
            <!-- <Tinymce ref="tinymce" v-model="comment" :height="300" menubar="false" /> -->
            <el-input v-model="comment" placeholder="请输入内容" :rows="10" type="textarea" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item>
            <el-badge value="new" class="item">
              <el-button size="mini" type="primary" @click="submitComment">评论</el-button>
            </el-badge>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item>
            <div class="form-info-title">
              <i class="el-icon-document" /><span>评论列表</span>
            </div>
            <div v-for="(item,index) in formItem.comment" :key="index" style="height:100px">
              <div class="info-title">
                <span>评论人：{{ item.userName }}</span>
                <div>
                  <span>评论时间：{{ item.createTime }}</span>
                </div>
              </div>
              <p v-html="item.content" />
              <div style="text-align: left;">
                <el-button size="mini" type="text" @click="approve(item)">支持&nbsp;({{ item.approve }})</el-button>
                <el-button size="mini" type="text" @click="opposition(item)">反对&nbsp;({{ item.opposition }})</el-button>
              </div>
              <!--星级评论-->
              <!-- <div class="block" style="text-align:right">
                <el-rate
                  v-model="value"
                  show-text
                />
              </div> -->
              <div class="line" />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
// import Tinymce from '@neu/biz-core/components/Tinymce'
import { create, update, detail, importUrl, deleteAttachmentByFsId, exportFile } from '@neu/dcom-ui/api/knowledge'
import { tree } from '@neu/dcom-ui/api/knowledgeType'
import * as commentApi from '@neu/dcom-ui/api/knowledgeComment'
import { clone } from '@neu/biz-core/utils/utils'
import { getToken } from '@neu/biz-core/utils/auth'
import { formatDate } from '@neu/biz-core/utils/utils'

// 定义一个表单原始项
const formItem = {
  /** 标题 */
  title: '',
  /** 类型 */
  knowledgeTypeCode: null,
  /** 内容 */
  content: '',
  // 附件列表
  attachment: [],
  // 关键字
  keywords: [],
  // 关键字名称列表
  // keywordsName: [],
  // 阅读量
  // readingVolume: '',
  // 创建人编码
  usercode: '',
  // 创建人名称
  username: '',
  /** 评论 */
  comments: []
}
export default {
  name: 'KonwledgeViewEdit',
  components: {
    // Tinymce
  },
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      value: null,
      colors: ['#99A9BF', '#F7BA2A', '#FF9900'],
      /** 评论 */
      comment: '',
      importUrl: importUrl,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Authentication': getToken()
      },
      availableOganizations: [],
      inspectionTypes: [],
      // 编辑的表单内容
      formItem: clone(formItem),
      // 表单验证规则
      rules: {
        title: [{ required: true, message: '标题不能为空', trigger: 'change' }],
        knowledgeTypeCode: [{ required: true, message: '类型不能为空', trigger: 'change' }]
      },
      test: ''
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: {
      handler() {
        if (this.id) {
          this.fetch()
        }
      },
      immediate: true
    }
  },
  created() {
    // findByDictionaryType('projectType').then(response => {
    //   this.projectTypes = response.data
    // })
    tree().then(response => {
      this.availableOganizations = response.data
    })
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          this.formItem = {
            ...response.data
          }
          this.formItem.createTime = formatDate(this.formItem.createTime)
          this.formItem.updateTime = formatDate(this.formItem.updateTime)
        })
      } else {
        this.formItem = clone(formItem)
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            if (updated) {
              resolve(update(this.id, this.formItem))
            } else {
              resolve(create(this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.editForm.resetFields()
      this.formItem = clone(this.formItem)
      this.comment = ''
    },

    handleBeforeUpLoad(file) {
      // if (file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
      //   this.$message({
      //     showClose: true,
      //     message: '文件 ' + file.name + ' 格式不正确，请上传.xls,.xlsx文件。',
      //     type: 'error'
      //   })
      // }
    },
    handleSuccess(response, file, fileList) {
      if (response.status === 'failure') {
        this.$message({
          showClose: true,
          message: response.data,
          type: 'error'
        })
      } else {
        this.$message({
          showClose: true,
          message: '文件上传成功',
          type: 'success'
        })
        const obj = {
          fsId: response.data.fsId,
          name: response.data.name
        }
        // console.log(obj)
        const fsIdArr = this.formItem.attachment.map(t => t.fsId)
        if (!fsIdArr.includes(obj.fsId)) {
          this.formItem.attachment.push(obj)
        } else {
          fileList.pop()
        }
      }
    },
    handleError(err, file, fileList) {
      //
      console.log(err)
    },
    handleRemove(file, fileList) {
      deleteAttachmentByFsId(file.fsId, this.id).then(res => {
        if (res.status === 'failure') {
          this.$message({
            showClose: true,
            message: res.data,
            type: 'error'
          })
        } else {
          this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          })
        }
      })
    },
    /** 删除某一项 */
    removeUser(tag) {
      this.formItem.keywords = this.formItem.keywords.filter(t => {
        return t.name !== tag.name
      })
    },
    /** 删除所有项 */
    clearAllUser() {
      this.formItem.keywords = []
    },
    add(value) {
      const keywordsName = this.formItem.keywords.map(t => t.name)
      if (!keywordsName.includes(value)) {
        const obj = {
          name: value
        }
        this.formItem.keywords.push(obj)
        this.test = ''
      }
      console.log(value)
    },
    /** 下载附件 */
    clickTag(tag) {
      exportFile(tag.fsId).then(res => {
        const content = res
        const blob = new Blob([content])
        const fileName = tag.name
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
      })
    },
    /** 提交评论 */
    submitComment() {
      if (this.comment === '') {
        return this.$message({
          showClose: true,
          message: '评论内容不能为空',
          type: 'error'
        })
      }
      commentApi.create(this.formItem.id, {
        content: this.comment
      }).then(res => {
        if (res.status === 'failure') {
          this.$message({
            showClose: true,
            message: res.data,
            type: 'error'
          })
        } else {
          this.$message({
            showClose: true,
            message: '评论成功',
            type: 'success'
          })
          this.fetch()
        }
      })
      this.comment = ''
    },
    approve(item) {
      let num = Number(item.approve)
      item.approve = ++num
      commentApi.update(item.id, item).then(res => {

      })
    },
    opposition(item) {
      let num = Number(item.opposition)
      item.opposition = ++num
      commentApi.update(item.id, item).then(res => {

      })
    }
  }
}
</script>
<style lang="scss" scoped>
.item {
  margin-top: 10px;
  margin-right: 40px;
}
.line {
  height:1px;
  border-bottom: 1px solid #e6ebf5;
}
/*自定义标题*/
.info-title{
  display: flex;
  align-items: center;
  // padding: 15px 0;
  margin-bottom: 15px;
  font-size: 12px;
  // border-bottom: 1px solid #e6ebf5;
  & > span{font-weight:bold; padding-left: 4px;}
  & > div{flex:1; text-align: right;  font-size: 10px;  color:#66AAF2;}
}
</style>

